package com.service.bracelet.common;

import com.service.bracelet.entity.User;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 缓存管理，自动根据请求user-agent判断浏览器还是app，app缓存30天，浏览器缓存60分钟
 */
public class CacheManager {

    // \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
    // 字符串在编译时会被转码一次,所以是 "\\b"
    // \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
    static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
            + "|windows (phone|ce)|blackberry"
            + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
            + "|laystation portable)|nokia|fennec|htc[-_]"
            + "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
    static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
            + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";

    //移动设备正则匹配：手机端、平板
    static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
    static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);

    /**
     * 检测是否是移动设备访问
     *
     * @return true:移动设备接入，false:pc端接入
     */
    public static boolean check(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT");
        if (null == userAgent) {
            userAgent = "";
        }
        // 匹配
        Matcher matcherPhone = phonePat.matcher(userAgent);
        Matcher matcherTable = tablePat.matcher(userAgent);
        String domain = request.getServerName();
        boolean isFromMobile = false;
        if (matcherPhone.find() || matcherTable.find() || (domain != null && domain.startsWith("m"))) {
            isFromMobile = true;
        }
        return isFromMobile;
    }

    /**
     * 设置缓存值
     * 注: 若已有该key值，则会先移除(会触发removalListener移除监听器)，再添加
     *
     * @param key
     * @param value
     */
    public static void put(String key, User value, HttpServletRequest request) {
        if (check(request)) {
            AppCacheManager.put(key, value);
        } else {
            BrowserCacheManager.put(key, value);
        }
    }

    /**
     * 获取缓存值
     * 注：如果键不存在值，将调用CacheLoader的load方法加载新值到该键中
     *
     * @param key
     * @return
     */
    public static User get(String key, HttpServletRequest request) {
        if (check(request)) {
            return AppCacheManager.get(key);
        } else {
            return BrowserCacheManager.get(key);
        }
    }

    /**
     * 移除cache内容
     *
     * @param key
     * @return
     */
    public static void remove(String key, HttpServletRequest request) {
        if (check(request)) {
            AppCacheManager.remove(key);
        } else {
            BrowserCacheManager.remove(key);
        }
    }
}
